package com.edroid.swingtest;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.border.Border;

public class Test extends JApplet {
	private String[] names = new String[] { "baseball player",
			"basketball player", "beach player", "chef", "hockey player" };
	private String[] pics = new String[] { "1.png", "2.png", "3.png", "4.png",
			"5.png" };

	public void init() {
		Container contentPane = getContentPane();
		ListModel model = new NameAndPictureListModel(names, pics);

		ListCellRenderer renderer = new NameAndPictureListCellRenderer();

		JList list = new JList(model);

		list.setCellRenderer(renderer);
		list.setVisibleRowCount(5);

		contentPane.setLayout(new FlowLayout());
		contentPane.add(new JScrollPane(list));
	}
}

class NameAndPictureListModel extends DefaultListModel {
	
	public NameAndPictureListModel(String[] names, String[] pics) {
		for (int i = 0; i < names.length; ++i) {
			addElement(new Object[] { names[i], new ImageIcon(pics[i]) });
		}
	}

	public String getName(Object object) {
		Object[] array = (Object[]) object;
		return (String) array[0];
	}

	public Icon getIcon(Object object) {
		Object[] array = (Object[]) object;
		return (Icon) array[1];
	}
}

class NameAndPictureListCellRenderer extends JLabel implements ListCellRenderer {
	private Border lineBorder = BorderFactory.createLineBorder(Color.red, 2),
			emptyBorder = BorderFactory.createEmptyBorder(2, 2, 2, 2);

	
	public NameAndPictureListCellRenderer() {
		setOpaque(true);
	}

	public Component getListCellRendererComponent(JList list, Object value,
			int index, boolean isSelected, boolean cellHasFocus) {
		NameAndPictureListModel model = (NameAndPictureListModel) list
				.getModel();

		setText(model.getName(value));
		setIcon(model.getIcon(value));

		if (isSelected) {
			setForeground(list.getSelectionForeground());
			setBackground(list.getSelectionBackground());
		} else {
			setForeground(list.getForeground());
			setBackground(list.getBackground());
		}

		if (cellHasFocus)
			setBorder(lineBorder);
		else
			setBorder(emptyBorder);

		return this;
	}
}
